package com.pattern.structural.flyweight.class02;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Ping
 * @date 2022/4/19 14:16
 **/
public class FlyweightDemo {
    Integer integer ;
    static int MAX_QUERY_NUM = 100000000 ;
    public static void main(String args[]) {
//
        Integer one = Integer.valueOf(120) ;
        Integer two = Integer.valueOf(120) ;
        Integer three = Integer.valueOf(1000) ;
        Integer four = Integer.valueOf(1000) ;
        System.out.println(three == four) ;

    }
}

class Ticket {
    private String from ;
    private String to ;
    private String time ;
    private int leftAmount ;

    public Ticket(String from, String to, String time, int leftAmount) {
        this.from = from;
        this.to = to;
        this.time = time;
        this.leftAmount = leftAmount;
    }

}
class TicketBasicInfor {
    private String from ;
    private String to ;
    private String time ;

    public TicketBasicInfor(String from, String to, String time) {
        this.from = from;
        this.to = to;
        this.time = time;
    }
}

class TicketFlyweight {
    /**
     * for sharing / sharable .
     */
    private TicketBasicInfor ticketBasic ;
    private int leftAmount ;

    public TicketFlyweight(TicketBasicInfor ticketBasic, int leftAmount) {
        this.ticketBasic = ticketBasic;
        this.leftAmount = leftAmount;
    }
}

/**
 * flyweight factory: managing these sharable objects, including, creat and use .
 * In our case, the sharable objects are those objects in TicketBasicInfor.
 */
class TicketFlyweightFactory {
    static Map<String, TicketBasicInfor> ticketBasicMap = new ConcurrentHashMap<>() ;
    static {
        ticketBasicMap.put("FUZHOU_XIAMEN_14", new TicketBasicInfor("FUZHOU", "XIAMEN", "14")) ;
    }
    public static TicketBasicInfor getTicketBasic(String key) {
        return ticketBasicMap.get(key) ;
    }

}


class TicketDAO {
    /**
     * key :  from_to_time
     * FUZHOU_XIAMEN_14
     * @param key
     * @return
     */
    public Ticket queryLeft(String key) {
        /**
         * query db to get some information
         */
        String[] parts = key.split("_") ;
        return new Ticket(parts[0], parts[1], parts[2], 170) ;
    }

    public TicketFlyweight queryTicketByFW(String key) {
        return new TicketFlyweight(TicketFlyweightFactory.getTicketBasic(key), 170) ;
    }

}


